<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择类型" clearable class="!w-240px">
          <el-option label="用户" :value="1" />
          <el-option label="商户" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="有效天数" prop="days">
        <el-input-number
          v-model="formData.days"
          :min="1"
          :max="3650"
          placeholder="请输入有效天数"
        />
      </el-form-item>
      <el-form-item label="销售价" prop="price">
        <el-input
          v-model="computedPrice"
          type="number"
          maxlength="8"
          :min="0.01"
          :max="99999999"
          :step="1"
          class="!w-120px !md-w-240px"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="原价" prop="linePrice">
        <el-input
          v-model="computedLinePrice"
          type="number"
          maxlength="8"
          :min="1"
          :max="99999999"
          :step="1"
          class="!w-120px !md-w-240px"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="formData.sort"
          :min="0"
          :max="99999999"
          placeholder="请输入显示顺序"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { CloudAllianceApi } from '@/api/member/cloud-alliance/package'
import { fenToYuan, yuanToFen } from '@/utils'

/** 加盟套餐 表单 */
defineOptions({ name: 'CloudAlliancePackageForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<any>({
  id: undefined,
  type: '',
  name: '',
  days: 0,
  price: '',
  linePrice: '',
  sort: 1
})
const formRules = reactive({
  type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  days: [{ required: true, message: '有效天数不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '销售价格不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const computedPrice = computed({
  get: () => fenToYuan(formData.value.price),
  set: (newValue: number) => {
    formData.value.price = yuanToFen(newValue)
  }
})
const computedLinePrice = computed({
  get: () => fenToYuan(formData.value.linePrice || formData.value.price),
  set: (newValue: number) => {
    formData.value.linePrice = yuanToFen(newValue)
  }
})

/** 打开弹窗 */
const open = async (type: string, id?: number | string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CloudAllianceApi.getDetail(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    data.linePrice = data.linePrice || data.price
    if (formType.value === 'create') {
      await CloudAllianceApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await CloudAllianceApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    type: '',
    name: '',
    days: 0,
    price: '',
    linePrice: '',
    sort: 1
  }
  formRef.value?.resetFields()
}
</script>
